package com.horay.springbootdemo.web.servlet.common.result;

import com.horay.springbootdemo.web.servlet.common.enums.ResultState;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * 响应结果实体
 *
 * @author heyingcheng
 * @date 2019/8/31 9:04
 */
@Setter
@ToString
public class ResultBody<T> {

    public static final ResultBody<String> RESULT_BODY_SUCCESS = new ResultBody();
    public static final ResultBody<String> RESULT_BODY_FAILURE = new ResultBody(ResultState.Failure);
    @Getter
    private int code;
    @Getter
    private String message;
    private T data;

    public ResultBody() {
        this(ResultState.Success, ResultState.Success.name().toUpperCase());
    }

    public ResultBody(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public ResultBody(ResultState resultState) {
        this(resultState, StringUtils.EMPTY);
    }

    public ResultBody(ResultState resultState, String message) {
        this(resultState, message, null);
    }

    public ResultBody(ResultState resultState, String message, T data) {
        this.code = resultState.code;
        this.message = message;
        this.data = data;
    }

    public ResultBody(T data) {
        this.code = ResultState.Success.code;
        this.message = ResultState.Success.name().toUpperCase();
        this.data = data;
    }

    public static final <E> ResultBody<E> success(E data) {
        return success(ResultState.Success.name().toUpperCase(), data);
    }

    public static final <E> ResultBody<E> success(String message, E data) {
        return new ResultBody(ResultState.Success, message, data);
    }

    public static final ResultBody<?> failure(String message) {
        return failure(ResultState.Failure.code, message);
    }

    public static final ResultBody<?> failure(int code, String message) {
        return new ResultBody(code, message, null);
    }

    public Object getMessage() {
        return getDefault(message);
    }

    public Object getData() {
        return getDefault(data);
    }

    private Object getDefault(Object object) {
        if (Objects.isNull(object)) {
            return StringUtils.EMPTY;
        } else {
            return object;
        }
    }

}